import Request from 'luch-request';
import { useFansStore } from '@/store/fans';
import env from '@/config/env';

const fansStore = useFansStore();
const http = new Request({
  baseURL: env.base_url,
  timeout: 8 * 1000,
  header: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

// 请求拦截
http.interceptors.request.use(
  (config) => {
    config.header = config.header || {};
    if (fansStore.fansinfo.refresh_token) {
      config.header.Authorization = 'Bearer ' + fansStore.fansinfo.refresh_token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截
http.interceptors.response.use(
  (response) => {
    const code: number = response.data.code;
    if (code == 200) {
      return response.data;
    }

    return Promise.reject(response.data);
  },
  (error) => {
    console.error(error);
    return Promise.reject(error.errMsg);
  }
);

export const refreshToken = () => {
  return new Promise((resolve, reject) => {
    http
      .request({
        method: 'POST',
        url: '/app/auth/refresh_token',
      })
      .then((res) => {
        console.log('新token');
        fansStore.fansinfo.token = res.data.token;
        if (res.data.refresh_token) {
          console.log('新refresh_token');
          fansStore.fansinfo.refresh_token = res.data.refresh_token;
        }
        resolve(true);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
